package top.zhangjianyong.blog.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import top.zhangjianyong.blog.enums.RespCode;
import top.zhangjianyong.blog.entity.po.UserSkill;
import top.zhangjianyong.blog.mapper.UserSkillMapper;
import top.zhangjianyong.blog.params.user.UserSkillSaveOrUpdateParam;
import top.zhangjianyong.blog.response.ApiResponse;
import top.zhangjianyong.blog.service.UserSkillService;

/**
 * 用户技能Service实现类
 *
 * @author zhangjianyong
 * @since 2024/7/1
 */
@Service
public class UserSkillServiceImpl extends ServiceImpl<UserSkillMapper, UserSkill>
    implements UserSkillService {

  @Override
  public ApiResponse listByUserId(Long userId) {
    LambdaQueryWrapper<UserSkill> wrapper = new LambdaQueryWrapper<>();
    wrapper
        .eq(UserSkill::getUserId, userId)
        .eq(UserSkill::getIsDel, 0)
        .orderByAsc(UserSkill::getSortOrder);

    List<UserSkill> skills = list(wrapper);
    return ApiResponse.success(skills);
  }

  @Override
  public ApiResponse saveOrUpdate(UserSkillSaveOrUpdateParam param) {
    UserSkill userSkill = new UserSkill();
    BeanUtils.copyProperties(param, userSkill);

    // 设置默认颜色
    if (StrUtil.isBlank(userSkill.getSkillColor())) {
      userSkill.setSkillColor("#3178C6");
    }

    // 设置默认排序
    if (userSkill.getSortOrder() == null) {
      userSkill.setSortOrder(0);
    }

    saveOrUpdate(userSkill);
    return ApiResponse.success();
  }

  @Override
  public ApiResponse deleteById(Long id) {
    return removeById(id) ? ApiResponse.success() : ApiResponse.fail(RespCode.FAIL);
  }

  @Override
  public ApiResponse updateSortOrder(List<UserSkillSaveOrUpdateParam> params) {
    for (UserSkillSaveOrUpdateParam param : params) {
      UserSkill userSkill = new UserSkill();
      userSkill.setId(param.id());
      userSkill.setSortOrder(param.sortOrder());
      updateById(userSkill);
    }
    return ApiResponse.success();
  }
}
